package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.HomeServiceDialog;
import com.asktgapp.model.HomeServiceDetailVO;
import com.asktgapp.model.HomeServiceVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.user.activity.FastPaymentActivity;
import com.asktgapp.user.activity.HomeServiceDetailActivity;
import com.asktgapp.user.activity.MainActivity;
import com.asktgapp.user.activity.PayActivity;
import com.asktgapp.user.activity.ServicePriceUpdateActivity;
import com.asktgapp.user.activity.UsedCheckActivity;
import com.asktgapp.utils.ImageDisplayUtil;

import java.util.Date;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上门服务详情页面
 */

public class HomeServiceDetailFragment extends BaseFragment {

    @InjectView(R.id.userHead)
    ImageView userHead;
    @InjectView(R.id.userName)
    TextView userName;
    @InjectView(R.id.userAddress)
    TextView userAddress;
    @InjectView(R.id.serviceType)
    TextView serviceType;
    @InjectView(R.id.serviceType2)
    TextView serviceType2;
    @InjectView(R.id.fault)
    TextView fault;
    @InjectView(R.id.deviceType)
    TextView deviceType;
    @InjectView(R.id.deviceBrand)
    TextView deviceBrand;
    @InjectView(R.id.deviceModel)
    TextView deviceModel;
    @InjectView(R.id.serviceTime)
    TextView serviceTime;
    @InjectView(R.id.deviceAddress)
    TextView deviceAddress;
    @InjectView(R.id.info)
    TextView info;
    @InjectView(R.id.name)
    TextView name;
    @InjectView(R.id.phone)
    TextView phone;
    @InjectView(R.id.commit)
    TextView commit;
    @InjectView(R.id.llEngineer)
    LinearLayout llEngineer;
    @InjectView(R.id.rvEngineer)
    RecyclerView rvEngineer;

    @InjectView(R.id.callPhone)
    LinearLayout callPhone;
    private String machineId, userID;
//    private String priceUnit = "元";

    private HomeServiceDetailVO serviceDetailVO;
    private BaseAdapter mBaseAdapter;
    boolean isResume = false;
    private String serverId;

    private void setUI() {
        if (serviceDetailVO == null)
            return;
//        ImageDisplayUtil.LoadNetImageWithUrl(userHead, getActivity(), serviceDetailVO.getServiceDetail().getUserPic());
        ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, serviceDetailVO.getServiceDetail().getUserPic());
        userName.setText(serviceDetailVO.getServiceDetail().getUserName());
        name.setText(serviceDetailVO.getServiceDetail().getService_user_name());
        String pro = serviceDetailVO.getServiceDetail().getProviceName().replaceAll("省", "");
        String city = serviceDetailVO.getServiceDetail().getCityName().replaceAll("市", "");
        if (TextUtils.isEmpty(pro + " " + city))
            userAddress.setText("未知地区");
        else
            userAddress.setText(pro + " " + city);


        deviceAddress.setText(serviceDetailVO.getServiceDetail().getProviceName() +
                serviceDetailVO.getServiceDetail().getCityName() + " " + serviceDetailVO.getServiceDetail().getService_address());
        String type = serviceDetailVO.getServiceDetail().getService_type();
        if (type.equals("1")) {
            serviceType.setText("维修");
            serviceType2.setText("上门维修");
        } else if (type.equals("2")) {
            serviceType.setText("检车");
            serviceType2.setText("上门检车");
        } else if (type.equals("3")) {
            serviceType.setText("保养");
            serviceType2.setText("上门保养");
        } else if (type.equals("4")) {
            serviceType.setText("评估");
            serviceType2.setText("上门评估");
        }

        fault.setText(serviceDetailVO.getServiceDetail().getService_info());
        deviceType.setText(serviceDetailVO.getServiceDetail().getTypeName());
        deviceBrand.setText(serviceDetailVO.getServiceDetail().getBrandName());
        deviceModel.setText(serviceDetailVO.getServiceDetail().getService_model());
        info.setText(serviceDetailVO.getServiceDetail().getService_other_infor());
//        Date date = Util.StrToDate(serviceDetailVO.getServiceDetail().getService_add_time(), "yyyy.MM.dd HH:mm:ss");
//        String timeStr = Utils.getAskTime(date);
        serviceTime.setText(serviceDetailVO.getServiceDetail().getService_time());

        if (userID.equals(serviceDetailVO.getServiceDetail().getService_user_id())) {
            phone.setText(serviceDetailVO.getServiceDetail().getService_user_tel());
            commit.setVisibility(View.GONE);
            if (serviceDetailVO.getServerProject().size() > 0) {
                llEngineer.setVisibility(View.VISIBLE);
                mBaseAdapter.setData(serviceDetailVO.getServerProject());
            }


        } else {
            phone.setText(serviceDetailVO.getServiceDetail().getService_user_tel().substring(0, 3) + "*********");
            if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                if (serviceDetailVO.getServerProject().size() > 0) {
                    serverId = serviceDetailVO.getServerProject().get(0).getServerId();
                    phone.setText(serviceDetailVO.getServiceDetail().getService_user_tel());
                    commit.setVisibility(View.GONE);
                    llEngineer.setVisibility(View.VISIBLE);
                    setHasOptionsMenu(true);
                    mBaseAdapter.setData(serviceDetailVO.getServerProject());
                    callPhone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Utils.callPhone(getActivity(), serviceDetailVO.getServiceDetail().getService_user_tel());
                        }
                    });
                }
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_home_service_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.finish, menu);
        menu.getItem(0).setTitle("取消收录");
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (checkIsLogin("登录后可体验更多内容"))
            cancelServerProject();
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView(View rootView) {

        getBaseActivity().setBackNavigationIcon();
        machineId = getActivity().getIntent().getStringExtra("id");
        userID = PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID);
        commit.setOnClickListener(this);
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_home_service_detail, parent, false),
                        new BaseViewHolder.Callbacks() {
                            @Override
                            public void bind(BaseViewHolder holder, Object data) {
                                if (data instanceof HomeServiceDetailVO.ServerProjectBean) {
                                    ImageView userHead = holder.getView(R.id.userHead);
                                    final HomeServiceDetailVO.ServerProjectBean bean = (HomeServiceDetailVO.ServerProjectBean) data;
                                    holder.setText(R.id.userName, bean.getUserName());
                                    holder.setText(R.id.serviceContent, bean.getServerRange());
                                    Date date = Util.StrToDate(bean.getTime(), "yyyy.MM.dd HH:mm:ss");
                                    String timeStr = Utils.getAskTime(date);
                                    holder.setText(R.id.addTime, timeStr);

                                    holder.setText(R.id.servicePrice, bean.getPrice() + "元");
//                                    ImageDisplayUtil.LoadNetImageWithUrl(userHead, getActivity(), bean.getUserPic());
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), userHead, bean.getUserPic());

                                    userHead.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent = new Intent(getActivity(), EngineerDetailActivity.class);
                                            intent.putExtra("id", bean.getProjectorId());
                                            startActivity(intent);
                                        }
                                    });
                                    if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {

                                        if (bean.getPayState().equals("1")) {
                                            holder.setText(R.id.serviceType, "报  价");
                                        } else if (bean.getPayState().equals("2")) {
                                            holder.setText(R.id.serviceType, "修  改");
                                        } else {
                                            holder.setText(R.id.serviceType, "已支付");
                                            setHasOptionsMenu(false);
                                        }
                                    } else {
//                                        if (bean.getPayState().equals("1")) {
//                                            holder.setText(R.id.serviceType, "未报价");
//                                        } else
                                        if (TextUtils.isEmpty(bean.getPrice()) || bean.getPrice().equals("0") || bean.getPrice().equals("0.0")) {
                                            holder.setText(R.id.serviceType, "未报价");
                                        } else {
                                            if (!bean.getPayState().equals("3")) {
                                                holder.setText(R.id.serviceType, "去支付");
                                            } else {
                                                holder.setText(R.id.serviceType, "已支付");
                                            }
                                        }

                                    }
                                    holder.getView(R.id.serviceType).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                                                //工程师 修改报价
                                                if (!bean.getPayState().equals("3")) {
                                                    Intent intent = new Intent(getActivity(), ServicePriceUpdateActivity.class);
                                                    intent.putExtra("id", bean.getServerId());
                                                    intent.putExtra("name", bean.getUserName());
                                                    intent.putExtra("price", bean.getPrice());
                                                    intent.putExtra("info", bean.getServerRange());
                                                    startActivity(intent);
                                                }

                                            } else {
                                                if (bean.getPayState().equals("2")) {
                                                    Intent intent = new Intent(getActivity(), PayActivity.class);
                                                    intent.putExtra("type", 4);
                                                    intent.putExtra("eg_user_id", bean.getProjectorId());
                                                    intent.putExtra("money", Double.valueOf(bean.getPrice()));
                                                    intent.putExtra("name", bean.getUserName());
                                                    intent.putExtra("eg_pic", bean.getUserPic());
//                                                Intent intent = new Intent(getActivity(), FastPaymentActivity.class);
                                                    intent.putExtra("targetId", bean.getServerId());
//                                                intent.putExtra("isReward", false);
                                                    startActivity(intent);
                                                }
                                            }
                                        }
                                    });
                                }
                            }

                            @Override
                            public void onItemClick(View view, int position) {
                            }
                        });

                return holder;
            }
        };
        rvEngineer.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rvEngineer.setNestedScrollingEnabled(false);
        rvEngineer.setAdapter(mBaseAdapter);
    }

    private void insertServerProject() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", userID);
        params.put("serviceId", machineId);
        params.put("page", 1);

        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.insertServerProject(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    HomeServiceDialog dialog = new HomeServiceDialog("已成功收录到您的订单\n联系电话：" + serviceDetailVO.getServiceDetail().getService_user_tel(),
                            "联系用户", new HomeServiceDialog.onResultCallBack() {
                        @Override
                        public void onSure() {
                            Utils.callPhone(getActivity(), serviceDetailVO.getServiceDetail().getService_user_tel());
                        }
                    });
                    dialog.show(getFragmentManager(), "HomeServiceDialog");
                    loadData();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    private void cancelServerProject() {
        if (Util.isEmpty(serverId)) {
            showTost("暂时无法取消收录", 0);
            return;
        }
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", userID);
        params.put("serverId", serverId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.cancelServerProject(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                getBaseActivity().finish();
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Override
    public void loadData() {
        visibleLoading();
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
            params.put("isEngineer", 1);
        } else {
            params.put("isEngineer", 0);
        }
        params.put("serviceId", machineId);
        params.put("page", 1);

        Call<ApiResponseBody<HomeServiceDetailVO>> call = apiservice.ServiceDetailByList(params);
        call.enqueue(new Callback<ApiResponseBody<HomeServiceDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<HomeServiceDetailVO>> call, Response<ApiResponseBody<HomeServiceDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    serviceDetailVO = response.body().getResult();
                    if (serviceDetailVO.getServiceDetail() != null)
                        setUI();
                    else {
                        getBaseActivity().finish();
                        showTost("数据错误", 1);
                    }

                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<HomeServiceDetailVO>> call, Throwable t) {
                inVisibleLoading();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isResume) {
            loadData();
        }
        isResume = true;
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.commit:
                if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                    insertServerProject();
                } else {
                    HomeServiceDialog dialog = new HomeServiceDialog("您还不是工程师，无法查看此信息\n请前往个人中心成为认证工程师后查看",
                            "好的", new HomeServiceDialog.onResultCallBack() {
                        @Override
                        public void onSure() {
                            Intent intent = new Intent(getActivity(), MainActivity.class);
                            intent.putExtra("flag", 222);
                            startActivity(intent);
                            getBaseActivity().onBackPressed();
                        }
                    });
                    dialog.show(getFragmentManager(), "HomeServiceDialog");
                }

                break;
        }
    }
}
